using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Input.Touch;
using Microsoft.Xna.Framework.Media;
using Perovich.GameObjects;
using Perovich.GameObjects.Components.TwoDimensional;
using Perovich.GameObjects.Components.ThreeDimensional;
using Perovich.GameObjects.Components;
using Perovich.GameObjects.Components.TwoDimensional.Particles;

namespace ThreeDExampleProject
{
    /// <summary>
    /// This is the main type for your game
    /// </summary>
    public class Game1 : ObjectGame
    {
        ModelObject3D ground;
        AttachableCamera gameCamera;
        Random random;
        FuelCarrier fuelCarrier;
        FuelCell[] fuelCells;
        Barrier[] barriers;
        Explosion exp;
        SmokeRing ring;


        public Game1()
        {
            Content.RootDirectory = "Content";

            this.BackgroundColor = Color.Black;

            // Frame rate is 30 fps by default for Windows Phone.
            TargetElapsedTime = TimeSpan.FromTicks(333333);

            // Extend battery life under lock.
            InactiveSleepTime = TimeSpan.FromSeconds(1);

            ground = new ModelObject3D(this);
            gameCamera = new AttachableCamera(this);

            //Initialize fuel cells
            fuelCells = new FuelCell[12];
            for (int index = 0; index < fuelCells.Length; index++)
            {
                fuelCells[index] = new FuelCell(this);
            }

            //Initialize barriers
            barriers = new Barrier[40];
            for (int index = 0; index < barriers.Length; index++)
            {
                barriers[index] = new Barrier(this);
            }
            fuelCarrier = new FuelCarrier(this);


            fuelCarrier.AddCollisionTargets(fuelCells);
            fuelCarrier.AddCollisionTargets(barriers);

            fuelCarrier.Collided += new EventHandler<CollisionEventArgs>(fuelCarrier_Collided);

            (Graphics as GraphicsDeviceManager).SupportedOrientations = DisplayOrientation.LandscapeLeft;
            (Graphics as GraphicsDeviceManager).PreferredDepthStencilFormat = DepthFormat.Depth24Stencil8;
            random = new Random();

            exp = new Explosion(this,1);
            ring = new SmokeRing(this,2);
            exp.Depth = 0;
            ring.Depth = 0.1f;

        }

        void fuelCarrier_Collided(object sender, CollisionEventArgs e)
        {
            if (e.Other is Barrier)
            {
                fuelCarrier.Backup();
            }
            else if (e.Other is FuelCell)
            {
                FuelCell FC = e.Other as FuelCell;
                if (!FC.Retrieved)
                {
                    Vector2 where = new Vector2(GraphicsDevice.Viewport.Width / 2, GraphicsDevice.Viewport.Height * 3 / 4);
                    exp.AddParticles(where);
                    ring.AddParticles(where);
                    FC.Retrieved = true;
                }
            }
        }

        /// <summary>
        /// Allows the game to perform any initialization it needs to before starting to run.
        /// This is where it can query for any required services and load any non-graphic
        /// related content.  Calling base.Initialize will enumerate through any components
        /// and initialize them as well.
        /// </summary>
        protected override void Initialize()
        {
            ground.Active = true;
            gameCamera.AttachTo(fuelCarrier,new Vector3(0, 7, -15),new Vector3(0, 5, 0));
            gameCamera.Active = true;
            gameCamera.FieldOfView = MathHelper.ToRadians(45.0f);
            gameCamera.NearClip = 1.0f;
            gameCamera.FarClip = 1000.0f;
            ground.AddCameras(gameCamera);

            


            foreach(FuelCell cell in fuelCells)
            {
                cell.LoadContent(Content, "Models/fuelcell");
                cell.Active = true;
                cell.AddCameras(gameCamera);
            }

            int randomBarrier = random.Next(3);
            string barrierName = null;

            foreach(Barrier bar in barriers)
            {

                switch (randomBarrier)
                {
                    case 0:
                        barrierName = "Models/cube10uR";
                        bar.BoundingSphereScale = 0.7f;
                        break;
                    case 1:
                        barrierName = "Models/cylinder10uR";
                        bar.BoundingSphereScale = 0.6f;
                        break;
                    case 2:
                        barrierName = "Models/pyramid10uR";
                        bar.BoundingSphereScale = 0.7f;
                        break;
                }
                bar.LoadContent(Content, barrierName);
                bar.Active = true;
                bar.AddCameras(gameCamera);
                randomBarrier = random.Next(3);
            }
            PlaceFuelCellsAndBarriers();

            //Initialize fuel carrier
            fuelCarrier.LoadContent(Content, "Models/fuelcarrier");
            fuelCarrier.Active = true;
            fuelCarrier.AddCameras(gameCamera);

            base.Initialize();

            gameCamera.AspectRatio = GraphicsDevice.Viewport.AspectRatio;
        }

        private void PlaceFuelCellsAndBarriers()
        {
            int min = 10;
            int max = 90;
            Vector3 tempCenter;

            //place fuel cells
            foreach (FuelCell cell in fuelCells)
            {
                cell.Position = GenerateRandomPosition(min, max);
                tempCenter = cell.BoundingSphere.Center;
                tempCenter.X = cell.Position.X;
                tempCenter.Z = cell.Position.Z;
                cell.BoundingSphere = new BoundingSphere(tempCenter,
                    cell.BoundingSphere.Radius);
                cell.Retrieved = false;
            }

            //place barriers
            foreach (Barrier barrier in barriers)
            {
                barrier.Position = GenerateRandomPosition(min, max);
                tempCenter = barrier.BoundingSphere.Center;
                tempCenter.X = barrier.Position.X;
                tempCenter.Z = barrier.Position.Z;
                barrier.BoundingSphere = new BoundingSphere(tempCenter,
                    barrier.BoundingSphere.Radius);
            }
        }

        private Vector3 GenerateRandomPosition(int min, int max)
        {
            int xValue, zValue;
            do
            {
                xValue = random.Next(min, max);
                zValue = random.Next(min, max);
                if (random.Next(100) % 2 == 0)
                    xValue *= -1;
                if (random.Next(100) % 2 == 0)
                    zValue *= -1;

            } while (IsOccupied(xValue, zValue));

            return new Vector3(xValue, 0, zValue);
        }

        private bool IsOccupied(int xValue, int zValue)
        {
            foreach (ModelObject3D currentObj in fuelCells)
            {
                if (((int)(MathHelper.Distance(
                    xValue, currentObj.Position.X)) < 15) &&
                    ((int)(MathHelper.Distance(
                    zValue, currentObj.Position.Z)) < 15))
                    return true;
            }

            foreach (ModelObject3D currentObj in barriers)
            {
                if (((int)(MathHelper.Distance(
                    xValue, currentObj.Position.X)) < 15) &&
                    ((int)(MathHelper.Distance(
                    zValue, currentObj.Position.Z)) < 15))
                    return true;
            }
            return false;
        }



        /// <summary>
        /// LoadContent will be called once per game and is the place to load
        /// all of your content.
        /// </summary>
        protected override void LoadContent()
        {
            ground.ObjectModel = Content.Load<Model>("Models/ground");

            // TODO: use this.Content to load your game content here
            base.LoadContent();
        }

        /// <summary>
        /// UnloadContent will be called once per game and is the place to unload
        /// all content.
        /// </summary>
        protected override void UnloadContent()
        {
            base.UnloadContent();
        }

        /// <summary>
        /// Allows the game to run logic such as updating the world,
        /// checking for collisions, gathering input, and playing audio.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        protected override void Update(GameTime gameTime)
        {
            // Allows the game to exit
            if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
                this.Exit();

            // TODO: Add your update logic here

            base.Update(gameTime);

            //Orange.GameObjects.Components.ComponentsExtensions.CheckColisions(this);
        }

        /// <summary>
        /// This is called when the game should draw itself.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        protected override void Draw(GameTime gameTime)
        {
            base.Draw(gameTime);
        }
    }
}
